﻿import sys, time;
import json

import bgtp.bgtp as bgtp
import games.XO.Rules.XOrules as XOrules
import games.XO.Rules.XOGameManager as XOGameManager
from platform.utilits import *
import Forms

gameName = "XO"

#деинициализация
class Client():
	def __init__(this):
		this.rules = None
		this.bgtp_mail = lambda x: 0
		this.stream = []
		this.gameFld = Forms.GameField()
	
	def start(this, gui_c):
		this.gui_c = gui_c
		
		#создаем либу в клиентском варианте, подписываемся на события, стартуем либу
		this.liba = bgtp.liba
		this.liba.init()
		this.liba.subscribe({}, 'stdout')
		this.liba.subscribe({}, this.stream)
		try:
			this.liba.startClient()
		except:
			Forms.MsgBox("Can't connect to server", "CONNECTION ERROR").open()		

	
	def bye(this, val):
		this.liba.stop()
		print "close"
		sys.exit()

	#эта ф-ция бесконечно разгребает очередь сообщений от сервака
	#и отображает их либо модальными мессенджами, либо отображая текущую ситуацию на поле
	def receve(this):
		if len(this.stream) == 0:
			return
		msg = this.stream.pop()
		
		req = Request(msg)
		
		#if client_msgs.count(req.type) <= 0:
		#	print "type", req.type, "is not client msg"
		#	return None

		eval("this." + req.type)(req)
	
	def send(this, type, msg = ""):
		try:
			this.liba.send(this.gui_c.name.value + ";" + type + ";" + json.dumps(msg))
		except:
			Forms.MsgBox("Can't connect to server" + msg, "CONNECTION ERROR").open()
	
	#след ряд функций занимается отсылкой серверу событий по нажатию кнопок
	def saveGame(this, val):
		msg = {};
		msg["GAME_FILE_NAME"] = "1";
		this.send("saveGame", msg);
	
	def loadGame(this, val):
		msg = {};
		msg["GAME_NAME"] = gameName;
		msg["GAME_FILE_NAME"] = "1";
		this.send("loadGame", msg)
	
	def startGame(this, val):
		this.send("startGame")

	def newGame(this, val):
		msg = {};
		msg["GAME_NAME"] = gameName;
		this.send("newGame", msg)
		#str(this.gui_c.sizeSelect.value)	
	
	def hi(this, val):
		this.send("hi")
	
	def addGamer(this, val):
		this.send("addGamer")
		if val != '"S"':
			time.sleep(0.5)			
			msg = {};
			msg["PARTY"] = val;
			this.send("setGamerParty", msg)

	def createAI(this, val):
		this.send("createAI")

	def getUserList(this, val):
		this.send("getUserList")
		
	def makeTurn(this, x, y):
		msg = {};
		msg["X"] = x;
		msg["Y"] = y;
		this.send("makeTurn", msg)
	
	def getSituation(this):
		this.send("getSituation")
		
	def getState(this):
		this.send("getState")
	
	#ф-ции для обработки ответов и уведомлений
	def msg(this, req):
		if req.usr == USR_GAMEMANAGER:
			if len(req.body) >= 3:
				this.rules.doRequest(Request(req.body))
				this.gameFld.paintGame(this.rules.data.fld, this.makeTurn, this.gui_c)
			else:
				Forms.MsgBox(req.body.get(ANS_TEXT), req.usr).open()
		elif req.usr == USR_SERVER:
			if len(req.body) >= 0 and str(req.body.get(MSG_TYPE)) == "newGame":
				this.getSituation()
			elif len(req.body) >= 0 and req.body.get(MSG_TYPE) == "startGame":
				this.getSituation()
			elif len(req.body) >= 0 and req.body.get(MSG_TYPE) == "stopGame":
				Forms.MsgBox("Game is over", "GAME").open()
			else:
				Forms.MsgBox(req.body.get(ANS_TEXT), "server msg").open()
		else:
			Forms.MsgBox(req.body.get(ANS_TEXT), req.usr).open()
	
	def return_loadGame(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()
		else:
			Forms.MsgBox("game loading", "save").open()
	
	def return_saveGame(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()
		else:
			Forms.MsgBox("game saving", "save").open()			
	
	def return_hi(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()
		else:
			this.getState()
	
	def return_addGamer(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()
	
	def return_setGamerParty(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()		
	
	def return_createAI(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()
	
	#def return_getUserList(this, req):
	#	dialog = Forms.UsersDialog(req.bodyText)
	#	dialog.open()
	
	def return_makeTurn(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(body[ANS_VAL], "false").open()
	
	def return_getSituation(this, req):
		if req.usr == USR_SERVER:
			if req.body.get(ANS_VAL) != False:
				if this.rules == None:
					this.rules = XOGameManager.XOGameManager(this.bgtp_mail)
					this.rules.client = True
				this.rules.setSituation(req.body.get(ANS_VAL))
				this.gameFld.paintGame(this.rules.data.fld, this.makeTurn, this.gui_c)
	
	def return_getState(this, req):
		if req.body.get(ANS_VAL) == KA_GAME:
			this.getSituation()
	
	def return_startGame(this, req):
		if req.body.get(ANS_VAL) == False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()
		elif req.body.get(ANS_VAL) == True:
			this.rules = XOGameManager.XOGameManager(this.bgtp_mail)
			this.rules.client = True
			this.getSituation()
	
	def return_newGame(this, req):
		if req.body [ANS_VAL]== False:
			Forms.MsgBox(req.body.get(ANS_TEXT), "false").open()
		elif req.body.get(ANS_VAL) == True:
			this.rules = XOGameManager.XOGameManager(this.bgtp_mail)
			this.rules.client = True
			#this.getSituation()